<template>
  <div class="default-column">

    <el-table v-loading="ruleListLoading" element-loading-text="拼命加载中"
              :data="ruleList" border stripe class="item-table" size="mini">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column align="center" prop="serviceList" label="客服ID列表">
        <template slot-scope="scope">
          <span v-for="item in scope.row.serviceList" style="margin: 5px; color: #409EFF">{{item.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="cron" label="cron时间"></el-table-column>
      <el-table-column align="center" prop="memo" label="备注"></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" size="mini" type="success">运行</el-tag>
          <el-tag v-else-if="scope.row.status === 0" size="mini" type="info">暂停</el-tag>
          <el-tag v-else size="mini" type="warning">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 0" type="text" size="mini" style="color: #409EFF" @click="changeTaskRuleStatus(scope.row)">运行</el-button>
          <el-button v-else type="text" size="mini" style="color: #909399" @click="changeTaskRuleStatus(scope.row)">暂停</el-button>
          <el-button type="text" size="mini" style="color: #F56C6C" @click="clickTriggerTaskRule(scope.row)">执行</el-button>
          <el-button type="text" size="mini" style="color: #1E90FF" @click="clickUpdateTaskRule(scope.row)">编辑</el-button>
          <el-button type="text" size="mini" style="color: red" @click="deleteTaskRule(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog title="更新回收规则" :visible.sync="dialogVisible" width="70%">
      <template>
        <el-row>
          <el-col :span="12">
            <el-transfer v-model="ruleInfo.ids" :data="personList" :titles="personTableTitle">
            </el-transfer>
          </el-col>

          <el-col :span="12">
            <el-form ref="form" :model="ruleInfo" :rules="formRules">
              <el-form-item label="规则描述">
                <el-input v-model="ruleInfo.memo" style="width: 60%;" placeholder="该分配规则描述"></el-input>
              </el-form-item>
              <el-form-item label="cron时间" prop="cron">
                <el-input v-model="ruleInfo.cron" style="width: 60%;" placeholder="cron表达式 [ 0 0 8 * * ? ] 表示每天8点的任务" ></el-input>
                <el-button type="primary" style="margin-left: 5px" @click="cronTextChange(ruleInfo.cron, true)">验证</el-button>
              </el-form-item>

              <div style="margin-top: 20px">
                <p style="color: firebrick">最近5次的运行时间</p>
                <p v-for="text in ruleInfo.cronText">
                  <el-tag size="mini" style="color: firebrick; margin-top: 5px">{{text}}</el-tag>
                </p>

                <hr style="margin: 5px"/>
                <p style="color: #6f7180">常用cron表达式</p>
                <p v-for="text in cronNoticeTexts">
                  <el-tag size="mini" style="color: #6f7180; margin-top: 5px">{{text}}</el-tag>
                </p>
              </div>
            </el-form>
          </el-col>
        </el-row>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false; ruleInfo = {}">取 消</el-button>
          <el-button type="primary" @click="clickTaskRule('form')">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    name: 'RecycleTask',
    data () {
      return {
        ruleListLoading: false,
        ruleList: [],

        // 编辑框数据
        dialogVisible: false,
        personTableTitle: ['待分配客服列表', '已选客服人员列表'],
        taskTypeTableTitle: ['待分配类型列表', '已分配类型列表'],
        personList: [],    // 待分配客服人员名单
        ruleInfo: {
          id: '',
          status: '',
          ids: [],
          types: [],
          cron: '',
          memo: '',
          allotment: 1, // 分配个数
          cronText: []
        },

        formRules: {
          cron: [
            { required: true, message: '请输入cron表达式', trigger: 'blur' },
            { min: 7, max: 255, message: '长度在 7 到 255 个字符', trigger: 'blur' }
          ]
        },
        cronNoticeTexts: [
          '"0 0 8 * * ?" - 每天上午8点触发',
          '"0 0 18 * * ?" - 每天下午6点触发',
          '"0 30 9 ? * MON-FRI" - 周一至周五的上午9:30触发',
          '"0 15 10 L * ?" 每月最后一日的上午10:15触发 ',
          '"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发 '
        ]
      }
    },
    created() {
      this.loadRuleList();
    },
    methods: {
      clickUpdateTaskRule(taskRule) {
        this.ruleInfo.id = taskRule.id;
        this.ruleInfo.status = taskRule.status;
        this.ruleInfo.ids = [];
        for (let i = 0; i < taskRule.serviceList.length; i++) {
          this.ruleInfo.ids.push(taskRule.serviceList[i].id);
        }
        this.ruleInfo.cron = taskRule.cron;
        this.ruleInfo.memo = taskRule.memo;
        this.ruleInfo.allotment = taskRule.allotment;

        this.loadPersonList();
        this.dialogVisible = true;
      },

      /**
       * 手动触发任务执行
       */
      clickTriggerTaskRule(taskRule) {
        this.$confirm('确认手动触发该回收任务？')
          .then(_ => {
            this.triggerTaskRule(taskRule.id);
          }).catch(_ => {});
      },
      async triggerTaskRule(id) {
        let data = await this.$$put('/rule/trigger', { id: id});
        if (this.checkResponse(data)) {
          this.$message.success("手动执行回收任务完成");
        }
      },

      clickTaskRule(form) {
        if (this.ruleInfo.ids === undefined || this.ruleInfo.ids === null || this.ruleInfo.length <= 0) {
          this.$message.error("已选客服人员列表为空");
          return;
        }
        if (this.ruleInfo.memo === undefined || this.ruleInfo.memo === null) {
          this.ruleInfo.memo = '';
        }

        this.$refs[form].validate((valid) => {
          if (valid) {
            this.updateTaskRule();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      async updateTaskRule() {
        let data = await this.$$put('/rule', {
          id: this.ruleInfo.id,
          status: this.ruleInfo.status,
          allotServiceId:  this.ruleInfo.ids.join(','),
          allotTaskCode:   this.ruleInfo.types.join(','),
          autoAllotTime: this.ruleInfo.cron,
          allotment: this.ruleInfo.allotment,
          memo:  this.ruleInfo.memo,
          type: 1
        });
        if (this.checkResponse(data)) {
          this.$message.success("更新回收规则成功");
          this.dialogVisible = false;
          this.loadRuleList();
        }
      },

      async changeTaskRuleStatus(taskRule) {
        if (taskRule.status !== 0 && taskRule.status !== 1) {
          return;
        }
        taskRule.status = taskRule.status === 1 ? 0 : 1;

        let data = await this.$$put('/rule/status/' + taskRule.status + '/' + taskRule.id);
        if (this.checkResponse(data)) {
          this.$message.success("更新任务状态成功");
          this.loadRuleList();
        }
      },
      deleteTaskRule(taskRule) {
        this.$confirm('此操作将删除该分配规则, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteTaskRuleInternal(taskRule);
        }).catch(e => {})
      },
      async deleteTaskRuleInternal(taskRule) {
        let data = await this.$$put('/rule/delete', {
          id: taskRule.id,
          allotServiceId:  taskRule.serviceIdList,
          allotTaskCode:   taskRule.taskCodeList,
          autoAllotTime: taskRule.cron,
          allotment: taskRule.allotment,
          memo:   taskRule.memo,
        });
        if (this.checkResponse(data)) {
          this.$message.success('删除成功!');
          this.loadRuleList();
        }
      },

      async loadRuleList() {
        this.ruleListLoading = true;
        let data = await this.$$post('/rule/page/list', {
          type: 1,
          current: 1,
          size: 100
        });
        this.ruleListLoading = false;
        if (this.checkResponse(data)) {
          data = data.data.data;
          this.ruleList = data.data;
        }
      },

      async cronTextChange(cron, show) {
        this.ruleInfo.cronText = [];
        if(typeof cron === "undefined" || cron === null || cron === '') {
          this.$message.error("cron表达式为空");
          return;
        }

        let data = await this.$$put("/rule/check/cron", { cron: cron });
        if (this.checkResponse(data)) {
          this.ruleInfo.cronText = data.data.data;
          if (show) {
//            this.$message.success("cron表达式正确");
          }
        }
      },
      loadPersonList() {
        this.personList = [];
        this.$$get('/customer/list').then(res => {
          if (this.checkResponse(res)) {
            res.data.data.forEach(person => {
              this.personList.push({
                key: person.id,
                label: person.name,
                disabled: false
              })
            })
          }
        })
      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
</style>
